package com.luoran.bartalks.action;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.beetl.sql.core.annotatoin.Param;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.core.UserContext;
import com.luoran.bartalks.core.ext.Pageable;
import com.luoran.bartalks.entity.BaseInfo;
import com.luoran.bartalks.entity.biz.BtPlanTemplate;
import com.luoran.bartalks.entity.biz.BtPlanTemplateEntry;
import com.luoran.bartalks.entity.biz.BtPosition;
import com.luoran.bartalks.entity.biz.BtRegion;
import com.luoran.bartalks.entity.biz.BtTransportMode;
import com.luoran.bartalks.service.IBtCodingRuleService;
import com.luoran.bartalks.service.IBtPlanTemplateEntryService;
import com.luoran.bartalks.service.IBtPlanTemplateService;
import com.luoran.bartalks.service.IBtPositionService;
import com.luoran.bartalks.service.IBtRegionService;
import com.luoran.bartalks.service.IBtTransportModeService;
import com.luoran.bartalks.utils.EnumBillType;

@Controller
@RequestMapping("/planTemplate")
public class BtPlanTemplateAction implements Pageable {
	@Autowired
	private IBtPlanTemplateService service;
	@Autowired
	private IBtRegionService iBtRegionService;
	@Autowired
	private IBtPlanTemplateEntryService iBtPlanTemplateEntryService;
	@Autowired
	private IBtTransportModeService transportModeService;
	@Autowired
	private IBtPositionService positionService;
	@Autowired
	private IBtCodingRuleService codingRuleService;

	private static final Logger log = LoggerFactory.getLogger(BtPlanTemplateAction.class);

	/**
	 * 区域管理列表数据
	 * 
	 * @return
	 */
	@Override
	public PageQuery<? extends BaseInfo> getQueryList(PageQuery<? extends BaseInfo> pageQuery) {
		log.info("获取计划模板列表数据,page:" + pageQuery.getPageNumber() + "size:" + pageQuery.getPageSize());
		@SuppressWarnings("unchecked")
		Map<String, String> map = (Map<String, String>) pageQuery.getParas();
		map.put("companyId", UserContext.get().getCompanyId());// 添加查询参数（公司ID）
		if (StringUtils.isEmpty(pageQuery.getOrderBy())) {
			pageQuery.setOrderBy("create_time DESC");
		}
		return service.getQueryList(pageQuery);
	}

	/**
	 * 计划模板列表页面
	 * 
	 * @return
	 */
	@RequestMapping
	public String queryTransport() {
		log.info("跳转到>>计划模板页面");
		return "planTemplate/planTemplate-list";
	}

	// 检查运输方式是否存在
	@GetMapping("getTransportMode")
	@ResponseBody
	public JSONObject getTransportMode() {
		log.info("获取运输信息》》");
		JSONObject res = new JSONObject();
		List<BtTransportMode> transportModes = transportModeService
				.getBtTransportModeByCompanyId(UserContext.get().getCompanyId());
		if (transportModes.isEmpty()) {
			res.put("state", true);
		} else {
			res.put("state", false);
		}
		return res;
	}

	// 新增计划模板
	@RequestMapping("addPlanTemplate")
	@ResponseBody
	public JSONObject addPlanTemplate(String startplace, String distination, String addremarks, String plantemplatecode,
			String plantemplatename, String transport, String distance, String signStr, String positionStr,
			String dayStr, String positionCodeStr) {
		log.info("新增计划模板信息》》");
		JSONObject res = new JSONObject();
		// 搜索是否已经存在
		BtPlanTemplate btPlanTemplate = service.getBtPlanTemplateByCode(plantemplatecode,
				UserContext.get().getCompanyId());
		if (btPlanTemplate != null) {
			res.put("msg", "编码已经被占用");
			return res;
		}
		// 运输方式信息
		BtTransportMode btTransportMode = transportModeService.getBtTransportMode(transport);
		// 无途经点保存
		if (signStr == null) {
			BtPlanTemplate planTemplate = new BtPlanTemplate();
			planTemplate.setPlanTemplateCode(plantemplatecode);
			planTemplate.setPlanTemplateName(plantemplatename);
			planTemplate.setCompanyCode(UserContext.get().getCompanyCode());
			planTemplate.setCompanyId(UserContext.get().getCompanyId());
			planTemplate.setTransportTypeId(btTransportMode.getId());
			planTemplate.setTransportCode(btTransportMode.getTransportCode());
			planTemplate.setTransportTypeName(btTransportMode.getTransportChineseName());
			if (!StringUtils.isEmpty(distance)) {
				planTemplate.setDistance(new BigDecimal(distance));
			}
			planTemplate.setRemarks(addremarks);
			planTemplate.setCreateTime(new Date());
			planTemplate.setFounder(UserContext.get().getId());
			planTemplate.setState(0);
			service.addPlanTemplate(planTemplate);
			res.put("msg", "新增成功");
			return res;
		}
		// 拆箱
		String[] sign = signStr.split(";");
		// String[] position = positionStr.split(";");
		String[] day = dayStr.split(";");
		String[] positionCode = positionCodeStr.split(";");
		// 位置信息
		BtPosition startplaceinfo = positionService.getPositByPositionCode(positionCode[0],
				UserContext.get().getCompanyId());
		BtRegion startplaceRegioninfo = iBtRegionService
				.getRegionByRegionCode(startplaceinfo.getParentRegPositionCode());
		BtPosition destinationinfo = positionService.getPositByPositionCode(positionCode[positionCode.length - 1],
				UserContext.get().getCompanyId());
		BtRegion destinationRegioninfo = iBtRegionService
				.getRegionByRegionCode(destinationinfo.getParentRegPositionCode());
		// 新增计划模版
		BtPlanTemplate planTemplate = new BtPlanTemplate();
		planTemplate.setPlanTemplateCode(plantemplatecode);
		planTemplate.setPlanTemplateName(plantemplatename);
		planTemplate.setCompanyCode(UserContext.get().getCompanyCode());
		planTemplate.setCompanyId(UserContext.get().getCompanyId());
		planTemplate.setStartPlaceId(startplaceinfo.getId());
		planTemplate.setStartPlaceName(startplaceinfo.getPositionName());
		planTemplate.setStartPlaceCode(startplaceinfo.getPositionCode());
		planTemplate.setStartPlaceRegName(startplaceRegioninfo.getRegionName());
		planTemplate.setDestinationName(destinationinfo.getPositionName());
		planTemplate.setDestinationId(destinationinfo.getId());
		planTemplate.setDestinationCode(destinationinfo.getPositionCode());
		planTemplate.setDestinationRegName(destinationRegioninfo.getRegionName());
		planTemplate.setTransportTypeId(btTransportMode.getId());
		planTemplate.setTransportCode(btTransportMode.getTransportCode());
		planTemplate.setTransportTypeName(btTransportMode.getTransportChineseName());
		if (!StringUtils.isEmpty(distance)) {
			planTemplate.setDistance(new BigDecimal(distance));
		}
		planTemplate.setRemarks(addremarks);
		planTemplate.setCreateTime(new Date());
		planTemplate.setFounder(UserContext.get().getId());
		planTemplate.setState(0);
		service.addPlanTemplate(planTemplate);
		// 途经点对象
		BtPlanTemplate btPlanTemplateforEntry = service.getBtPlanTemplateByCode(plantemplatecode,
				UserContext.get().getCompanyId());
		for (int j = 0; j < sign.length; j++) {
			BtPlanTemplateEntry PlanTemplateEntry = new BtPlanTemplateEntry();
			BtPosition placeinfo = positionService.getPositByPositionCode(positionCode[j],
					UserContext.get().getCompanyId());
			BtRegion placeRegioninfo = iBtRegionService.getRegionByRegionCode(placeinfo.getParentRegPositionCode());
			PlanTemplateEntry.setPlanTemplateId(btPlanTemplateforEntry.getId());
			PlanTemplateEntry.setCompanyId(UserContext.get().getCompanyId());
			PlanTemplateEntry.setRegPositionName(placeRegioninfo.getRegionName());
			PlanTemplateEntry.setPositionId(placeinfo.getId());
			PlanTemplateEntry.setPositionCode(placeinfo.getPositionCode());
			PlanTemplateEntry.setPositionName(placeinfo.getPositionName());
			PlanTemplateEntry.setSign(Integer.parseInt(sign[j]));
			PlanTemplateEntry.setDays(Integer.parseInt(day[j]));
			PlanTemplateEntry.setStatus(1);
			PlanTemplateEntry.setCreateTime(new Date());
			PlanTemplateEntry.setFounder(UserContext.get().getId());
			iBtPlanTemplateEntryService.addBtPlanTemplateEntry(PlanTemplateEntry);
		}
		res.put("msg", "新增成功");
		return res;
	}

	// 新增时得到部分计划模板的信息
	@GetMapping("getAddPlanTemplate")
	@ResponseBody
	public JSONObject getPlanTemplate() {
		log.info("获取计划模板信息》》");
		JSONObject res = new JSONObject();
		List<BtTransportMode> transportModes = transportModeService
				.getBtTransportModeByCompanyId(UserContext.get().getCompanyId());
		List<BtPlanTemplate> planTemplates = service.getBtPlanTemplateByCompanyId(UserContext.get().getCompanyId());
		List<BtPosition> btRegPositions = positionService.getPositionByCompanyId(UserContext.get().getCompanyId());
		JSONObject generateCoding = codingRuleService.generateCoding(EnumBillType.PLANTEMPLATE,
				UserContext.get().getCompanyId());
		res.put("transportModes", transportModes);
		res.put("planTemplates", planTemplates);
		res.put("btRegPositions", btRegPositions);
		res.put("generateCoding", generateCoding);
		res.put("state", true);
		return res;
	}

	// 编辑时根据id获取计划模板信息
	@GetMapping("/getEditPlanTemplate/{id}")
	@ResponseBody
	public JSONObject getPlanTemplate(@PathVariable("id") String id) {
		log.info("根据Id 获取计划模板信息》》");
		JSONObject res = new JSONObject();
		BtPlanTemplate planTemplate = service.getPlanTemplateById(id);
		List<BtPlanTemplateEntry> planTemplateList = iBtPlanTemplateEntryService.getBtPlanTemplateEntryByParentId(id,
				UserContext.get().getCompanyId());
		List<BtTransportMode> transportModes = transportModeService
				.getBtTransportModeByCompanyId(UserContext.get().getCompanyId());
		List<BtPosition> btPositions = positionService.getPositionByCompanyId(UserContext.get().getCompanyId());
		res.put("transportModes", transportModes);
		res.put("planTemplateList", planTemplateList);
		if (planTemplateList.size() > 0) {
			if (planTemplateList.size() == 1) {
				res.put("positionSet", planTemplateList.get(0).getPositionCode());
			} else if (planTemplateList.size() > 1) {
				List<String> list = new ArrayList<>();
				for (int i = 0; i < planTemplateList.size(); i++) {
					list.add(planTemplateList.get(i).getPositionCode());
				}
				String positionSet = StringUtils.collectionToDelimitedString(list, ",");
				res.put("positionSet", positionSet);
			}
		} else {
			res.put("positionSet", null);
		}
		res.put("btPositions", btPositions);
		res.put("obj", planTemplate);
		res.put("state", true);
		return res;
	}

	// 根据id逻辑删除计划模板
	@RequestMapping("/deletePlanTemplate/{id}")
	@ResponseBody
	public JSONObject deletePlanTemplate(@PathVariable("id") String id) {
		log.info("删除计划模板信息》》");
		JSONObject res = new JSONObject();
		service.deleteBtPlanTemplateById(id);
		res.put("msg", "删除成功！");
		res.put("state", true);
		return res;
	}

	// 编辑后保存
	@RequestMapping("editPlanTemplate")
	@ResponseBody
	public JSONObject editPlanTemplate(String plantemplateid, String startplace, String distination, String addremarks,
			String plantemplatecode, String plantemplatename, String transport, String distance, String signStr,
			String positionStr, String dayStr, String positionCodeStr) {
		log.info("新增计划模板信息》》");
		JSONObject res = new JSONObject();
		// 运输方式信息
		BtTransportMode btTransportMode = transportModeService.getBtTransportMode(transport);
		// 清理途经点信息
		iBtPlanTemplateEntryService.deleteBtPlanTemplateEntryByPlanTemplateId(plantemplateid);
		// 无途经点保存
		if (signStr == null) {
			BtPlanTemplate planTemplate = new BtPlanTemplate();
			planTemplate.setId(plantemplateid);
			planTemplate.setPlanTemplateCode(plantemplatecode);
			planTemplate.setPlanTemplateName(plantemplatename);
			planTemplate.setCompanyCode(UserContext.get().getCompanyCode());
			planTemplate.setCompanyId(UserContext.get().getCompanyId());
			planTemplate.setTransportTypeId(btTransportMode.getId());
			planTemplate.setTransportCode(btTransportMode.getTransportCode());
			planTemplate.setTransportTypeName(btTransportMode.getTransportChineseName());
			if (!StringUtils.isEmpty(distance)) {
				planTemplate.setDistance(new BigDecimal(distance));
			}
			planTemplate.setRemarks(addremarks);
			planTemplate.setCreateTime(new Date());
			planTemplate.setFounder(UserContext.get().getId());
			planTemplate.setState(0);
			service.updateBtPlanTemplateById(planTemplate);
			res.put("msg", "修改成功");
			return res;
		}
		// 拆箱
		String[] sign = signStr.split(";");
		// String[] position = positionStr.split(";");
		String[] day = dayStr.split(";");
		String[] positionCode = positionCodeStr.split(";");
		// 位置信息
		BtPosition startplaceinfo = positionService.getPositByPositionCode(positionCode[0],
				UserContext.get().getCompanyId());
		BtRegion startplaceRegioninfo = iBtRegionService
				.getRegionByRegionCode(startplaceinfo.getParentRegPositionCode());
		BtPosition destinationinfo = positionService.getPositByPositionCode(positionCode[positionCode.length - 1],
				UserContext.get().getCompanyId());
		BtRegion destinationRegioninfo = iBtRegionService
				.getRegionByRegionCode(destinationinfo.getParentRegPositionCode());
		// 修改计划模版
		BtPlanTemplate planTemplate = new BtPlanTemplate();
		planTemplate.setId(plantemplateid);
		planTemplate.setPlanTemplateCode(plantemplatecode);
		planTemplate.setPlanTemplateName(plantemplatename);
		planTemplate.setCompanyCode(UserContext.get().getCompanyCode());
		planTemplate.setCompanyId(UserContext.get().getCompanyId());
		planTemplate.setStartPlaceId(startplaceinfo.getId());
		planTemplate.setStartPlaceName(startplaceinfo.getPositionName());
		planTemplate.setStartPlaceCode(startplaceinfo.getPositionCode());
		planTemplate.setStartPlaceRegName(startplaceRegioninfo.getRegionName());
		planTemplate.setDestinationName(destinationinfo.getPositionName());
		planTemplate.setDestinationId(destinationinfo.getId());
		planTemplate.setDestinationCode(destinationinfo.getPositionCode());
		planTemplate.setDestinationRegName(destinationRegioninfo.getRegionName());
		planTemplate.setTransportTypeId(btTransportMode.getId());
		planTemplate.setTransportCode(btTransportMode.getTransportCode());
		planTemplate.setTransportTypeName(btTransportMode.getTransportChineseName());
		if ("".equals(distance)) {
			BigDecimal b = null;
			planTemplate.setDistance(b);
		} else {
			planTemplate.setDistance(new BigDecimal(distance));
		}
		planTemplate.setRemarks(addremarks);
		planTemplate.setCreateTime(new Date());
		planTemplate.setFounder(UserContext.get().getId());
		planTemplate.setState(0);
		service.updateBtPlanTemplateById(planTemplate);
		// 途经点对象
		iBtPlanTemplateEntryService.deleteBtPlanTemplateEntryById(plantemplateid);
		BtPlanTemplate btPlanTemplateforEntry = service.getBtPlanTemplateByCode(plantemplatecode,
				UserContext.get().getCompanyId());
		for (int j = 0; j < sign.length; j++) {
			BtPlanTemplateEntry PlanTemplateEntry = new BtPlanTemplateEntry();
			BtPosition placeinfo = positionService.getPositByPositionCode(positionCode[j],
					UserContext.get().getCompanyId());
			BtRegion placeRegioninfo = iBtRegionService.getRegionByRegionCode(placeinfo.getParentRegPositionCode());
			PlanTemplateEntry.setPlanTemplateId(btPlanTemplateforEntry.getId());
			PlanTemplateEntry.setCompanyId(UserContext.get().getCompanyId());
			PlanTemplateEntry.setRegPositionName(placeRegioninfo.getRegionName());
			PlanTemplateEntry.setPositionId(placeinfo.getId());
			PlanTemplateEntry.setPositionCode(placeinfo.getPositionCode());
			PlanTemplateEntry.setPositionName(placeinfo.getPositionName());
			PlanTemplateEntry.setSign(Integer.parseInt(sign[j]));
			PlanTemplateEntry.setDays(Integer.parseInt(day[j]));
			PlanTemplateEntry.setStatus(1);
			PlanTemplateEntry.setCreateTime(new Date());
			PlanTemplateEntry.setFounder(UserContext.get().getId());
			iBtPlanTemplateEntryService.addBtPlanTemplateEntry(PlanTemplateEntry);
		}
		res.put("msg", "修改成功");
		return res;
	}

	@GetMapping("/findPosition/{longNumber}")
	@ResponseBody
	public JSONObject findPosition(@Param("longNumber") String longNumber) {
		log.info("查找位置信息》》");
		JSONObject res = new JSONObject();
		return res;
	}

	@GetMapping("addJournalPlanTemplate")
	@ResponseBody
	public JSONObject addJournalPlanTemplate(String id, String destination)
			throws ParseException, InterruptedException {
		log.info("新增分录计划模板信息》》");
		JSONObject res = new JSONObject();
		BtPosition position = positionService.getPositByPositionCode(destination, UserContext.get().getCompanyId());
		res.put("position", position);
		res.put("state", true);
		return res;
	}

	// 根据位置编码查询位置信息
	@RequestMapping("findPositionByCode")
	@ResponseBody
	public JSONObject findPositionByCode(String positionCode) {
		log.info("根据位置编码查询位置信息》》");
		JSONObject res = new JSONObject();
		BtPosition btRegPosition = positionService.getPositByPositionCode(positionCode,
				UserContext.get().getCompanyId());
		res.put("btRegPosition", btRegPosition);
		return res;
	}

}
